# -*- coding: utf-8 -*-
# Created by liangfuting on 2020/9/2
# Copyright (c) 2020 liangfuting. All rights reserved.

# -*- coding: utf-8 -*-
# Created by liangfuting on 2020/8/19
# Copyright (c) 2020 liangfuting. All rights reserved.
from django.urls import path
from django.shortcuts import render, redirect,reverse,HttpResponse
from stark.service.v1 import StarkHandler,BootStrapModelForm,get_datetime_text,get_choice_text,get_manytomany
# from stark.forms.widgets import DateTimePickerInput
from django.utils.safestring import mark_safe
from django import forms
from web import models


class PaymentRecordModelForm(BootStrapModelForm):
    class Meta:
        model=models.PaymentRecord
        fields = ["pay_type", 'paid_fee','class_list','note']
        # exclude = ['customer','consultant']
        # fields=["pay_type",'paid_fee','class_list','confirm_user','confirm_status','confirm_date']
        # widgets={
        #     'apply_date':DateTimePickerInput,
        #     'confirm_date': DateTimePickerInput,
        # }

class StudentPaymentRecordModelForm(BootStrapModelForm):
    qq=forms.CharField(label='QQ号',max_length=32)
    mobile=forms.CharField(label='手机号',max_length=32)
    emergency_contract=forms.CharField(label='紧急联系人电话', max_length=32)
    class Meta:
        model=models.PaymentRecord
        fields=["pay_type", 'paid_fee','class_list','qq','mobile','emergency_contract','note']

class PaymentRecordHandler(StarkHandler):
    list_display=[get_choice_text('缴费类型',"pay_type"),'paid_fee','consultant','class_list','consultant',
                  get_choice_text('状态','confirm_status')]
    # model_form_class = PaymentRecordModelForm
    # change_list_template = 'web/payment_record.html'

    def get_model_form_class(self,is_add,request,pk,*args,**kwargs):
        customer_id = kwargs.get('customer_id')
        student_exists=models.Student.objects.filter(customer_id=customer_id).exists()
        #如果学生存在就返回缴费记录，如果不存在时，第一次缴费要添加学生信息
        if student_exists:
            return PaymentRecordModelForm
        return StudentPaymentRecordModelForm


    def get_list_display(self):
        value=[]
        if self.list_display:
            value.extend(self.list_display)
        return value

    def get_urls(self):
        #若子类继承，可修改返回列表值
        # print(self.get_add_url_name,self.get_list_url_name,self.get_edit_url_name,self.get_del_url_name)
        patterns=[]
        #原始方法
        # patterns.append(path('list/',self.list_view,name="{}_{}_list".format(self.app_label, self.model_name)))
        # patterns.append(path('add/', self.add_view, name="{}_{}_add".format(self.app_label, self.model_name)))
        # patterns.append(path('edit/<int:pk>/', self.change_view, name="{}_{}_edit".format(self.app_label, self.model_name)))
        # patterns.append(path('delete/<int:pk>/', self.delete_view, name="{}_{}_delete".format(self.app_label, self.model_name)))
        patterns.append(path('list/<int:customer_id>/',self.wapper(self.list_view),name=self.get_list_url_name))
        patterns.append(path('add/<int:customer_id>/', self.wapper(self.add_view), name=self.get_add_url_name))
        # 只能查看和添加，不能编辑和删除，涉及到钱，事关重大
        # patterns.append(path('edit/<int:customer_id>/<int:pk>/', self.wapper(self.change_view), name=self.get_edit_url_name))
        # patterns.append(path('delete/<int:customer_id>/<int:pk>/', self.wapper(self.delete_view), name=self.get_del_url_name))
        # print(self.extra_urls())

        patterns.extend(self.extra_urls())
        # print(patterns)
        return patterns

    def get_query_set(self,request,*args,**kwargs):

        # print(request.session.keys())
        # if 'user_info' not in request.session:
        #     # print(reverse('login'))
        #     return redirect(reverse('login'))
        customer_id=kwargs.get('customer_id')

        user_id = request.session['user_info']['id']
        # print(customer_id,user_id)
        #客户的顾问ID是当前用户时，才能访问跟进记录
        return self.model_class.objects.filter(customer_id=customer_id,customer__consultant_id=user_id)

    def save(self,request,form,is_update,*args,**kwargs):
        user_id = request.session['user_info']['id']
        customer_id = kwargs.get('customer_id')
        object_exists=models.Customer.objects.filter(id=customer_id,consultant_id=user_id).exists()
        if not object_exists:
            return HttpResponse('非法操作')
        if not is_update:
            #新增用户
            form.instance.consultant_id=user_id
            form.instance.customer_id=customer_id
        #更新用户信息
        form.save()
        #创建学员信息
        class_list=form.cleaned_data['class_list']
        fetch_student_object=models.Student.objects.filter(customer_id=customer_id).first()
        if not fetch_student_object:
            qq=form.cleaned_data['qq']
            mobile=form.cleaned_data['mobile']
            emergency_contract=form.cleaned_data['emergency_contract']
            student_object=models.Student.objects.create(customer_id=customer_id,qq=qq,mobile=mobile,
                                                         emergency_contract=emergency_contract)
            student_object.class_list.add(class_list)
        else:
            fetch_student_object.class_list.add(class_list)


    # def get_add_btn(self,request,*args,**kwargs):
    #     #子类可继承函数，预留此钩子函数
    #     if self.has_add_btn:
    #         # customer_id=kwargs.get('customer_id')
    #         target_url=self.reverse_add_url(*args,**kwargs)
    #         # reverse("stark:web_consultrecord_add", kwargs={'customer_id': customer_id})
    #         return "<a class='btn btn-success' href='{}'>添加</a>".format(target_url)
    #     return None

    # def get_change_object(self,request,pk,*args,**kwargs):
    #     user_id = request.session['user_info']['id']
    #     customer_id = kwargs.get('customer_id')
    #     # print(user_id,customer_id,args,kwargs)
    #     return self.model_class.objects.filter(pk=pk,customer_id=customer_id,customer__consultant_id=user_id).first()
    #
    # def delete_object(self,request,pk,*args,**kwargs):
    #     user_id = request.session['user_info']['id']
    #     customer_id = kwargs.get('customer_id')
    #     # print(user_id, customer_id, args, kwargs)
    #     record_queryset=self.model_class.objects.filter(pk=pk,customer_id=customer_id,customer__consultant_id=user_id).first()
    #     if not record_queryset:
    #         return HttpResponse('要删除的记录不存在，请重新选择')
    #     record_queryset.delete()


    # def get_list_display(self):
    #     '''
    #     获取页面上应该显示的列,预留页面的钩子方法，子类可继承方法，进行扩展
    #     :return:
    #     '''
    #     value = []
    #     # if self.list_display:
    #     value.extend(self.list_display)
    #         # value.extend([StarkHandler.display_edit, StarkHandler.display_del])
    #     #添加自己类的display_edit_del方法
    #     value.append(type(self).display_edit_del)
    #     value.insert(0,type(self).display_check)
    #     # print(value)
    #     return value


    def display_edit_del(self,obj=None,is_header=None,*args,**kwargs):
        if is_header:
            return '操作'
        # print(kwargs)
        customer_id = kwargs.get('customer_id')
        # edit_url=self.reverse_change_url(pk=obj.pk,customer_id=customer_id)
        # del_url = self.reverse_del_url(pk=obj.pk,customer_id=customer_id)
        return mark_safe("<a href='{}'><i class='fa fa-edit' aria-hidden='true'></i> 编辑</a> <a href='{}'><i class='fa fa-trash-o'></i> 删除</a>".format("#","#"))



